<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from 'vue';

import { message, Modal } from 'ant-design-vue';
import dayjs from 'dayjs';

// 导入公共宠物选择组件
import PetSelector from '../components/PetSelector.vue';
import CaseManagementModal from './components/CaseManagementModal.vue';
// 导入住院组组件
import InpatientGroup from './components/InpatientGroup.vue';
// 导入病历表单组件
import MedicalRecordForm from './components/MedicalRecordForm.vue';

// 接口定义
interface Pet {
  id: string;
  name: string;
  type: string;
  age?: string; // 改为string类型以兼容公共组件
  breed?: string;
  gender?: string;
  neutered?: string; // 改为string类型以兼容公共组件
  ownerName: string;
  ownerPhone: string;
  contact: string;
  doctor: string;
  phone: string;
}

interface MedicalRecord {
  id: string;
  recordNumber: string;
  recordDate: any;
  doctor: string;
  complaint: string;
  temperature?: number;
  weight?: number;
  respiration?: number;
  heartRate?: number;
  examination: {
    abdominalPalpation: string;
    bonesMuscles: string;
    earsEyesMouthNose: string;
    heartLungs: string;
    lymphNodes: string;
    skinCoat: string;
  };
  date: string;
  time?: string;
  // 新增字段
  labTests?: any[];
  diagnosis?: string;
  treatmentPlan?: string;
  prescriptions?: any[];
  surgeries?: any[];
  treatments?: any[];
  doctorAdvice?: string;
  precautions?: string;
  followUpDate?: any;
  // 病历状态：draft-草稿，confirmed-已确认
  status?: 'confirmed' | 'draft';
}

interface TodayRegistration {
  id: string;
  petId: string;
  petName: string;
  ownerName: string;
  petType: string;
  doctor: string;
  contact: string;
}

interface PetTab {
  id: string;
  pet: Pet;
  medicalRecords: MedicalRecord[];
  currentRecord: MedicalRecord | null;
  formData: any;
  isModified: boolean;
  createTime: string;
  // 住院相关字段
  inpatientGroups: any[];
  inpatientGroupsinpatientGroups;
  currentInpatientGroup: any | null;
  currentInpatientGroup;
  inpatientFormData: any;
  // 住院病历相关字段
  inpatientRecords: MedicalRecord[];
  inpatientRecordsinpatientRecords;
}

// 响应式数据
const activeTabKey = ref<string>('');
const petTabs = ref<PetTab[]>([]);
const recordsTab = ref('case');
const petSelectionTab = ref('today');
const searchQuery = ref('');
const todaySearchQuery = ref('');

// 病例管理相关
const caseManagementVisible = ref(false);
const selectedPetForCase = ref<null | Pet>(null);

// 模拟数据
const pets = ref<Pet[]>([]);
const todayRecords = ref<MedicalRecord[]>([]);
const todayRegistrations = ref<TodayRegistration[]>([]);
const inpatientGroupRef = ref(null);

// 计算属性
const filteredPets = computed(() => {
  if (!searchQuery.value) return pets.value;

  return pets.value.filter(
    (pet) =>
      pet.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      pet.ownerName.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      pet.contact.includes(searchQuery.value),
  );
});

const filteredTodayRegistrations = computed(() => {
  if (!todaySearchQuery.value) return todayRegistrations.value;

  return todayRegistrations.value.filter(
    (registration) =>
      registration.petName
        .toLowerCase()
        .includes(todaySearchQuery.value.toLowerCase()) ||
      registration.ownerName
        .toLowerCase()
        .includes(todaySearchQuery.value.toLowerCase()) ||
      registration.contact.includes(todaySearchQuery.value),
  );
});

const currentTab = computed(() => {
  return petTabs.value.find((tab) => tab.id === activeTabKey.value);
});

// 方法
const selectPet = (pet: null | Pet) => {
  if (!pet) return;

  // 检查是否已经存在该宠物的标签页
  const existingTab = petTabs.value.find((tab) => tab.pet.id === pet.id);

  if (existingTab) {
    // 如果已存在，切换到该标签页
    activeTabKey.value = existingTab.id;
    // 确保该标签页的病历记录已加载
    if (existingTab.medicalRecords.length === 0) {
      loadPetRecords(pet.id, existingTab);
    }
  } else {
    // 如果不存在，创建新的标签页
    const newTab: PetTab = {
      id: `tab_${pet.id}_${Date.now()}`,
      pet,
      medicalRecords: [],
      currentRecord: null,
      formData: null,
      isModified: false,
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      // 住院相关字段
      inpatientGroups: [],
      currentInpatientGroup: null,
      inpatientFormData: {
        admissionDate: dayjs(),
        conditionType: '',
        responsibleDoctor: '',
        dischargeMethod: 'manual',
        dischargeDate: null,
        remarks: '',
      },
      // 住院病历相关字段
      inpatientRecords: [],
    };

    petTabs.value.push(newTab);
    activeTabKey.value = newTab.id;

    // 加载该宠物的病历记录
    loadPetRecords(pet.id, newTab);
  }
};

const selectPetFromRegistration = (registration: TodayRegistration) => {
  const pet = pets.value.find((p) => p.id === registration.petId);
  if (pet) {
    selectPet(pet);
  }
};

const closeTab = (targetKey: string) => {
  const targetIndex = petTabs.value.findIndex((tab) => tab.id === targetKey);

  if (targetIndex !== -1) {
    petTabs.value.splice(targetIndex, 1);

    // 如果关闭的是当前激活的标签页，切换到其他标签页
    if (activeTabKey.value === targetKey) {
      activeTabKey.value =
        petTabs.value.length > 0
          ? petTabs.value[Math.min(targetIndex, petTabs.value.length - 1)].id
          : '';
    }
  }
};

const selectRecord = (record: MedicalRecord) => {
  const currentTabData = currentTab.value;
  if (currentTabData) {
    currentTabData.currentRecord = record;

    // 根据选择的病历记录更新formData
    const newFormData = {
      recordDate: record.recordDate || dayjs(),
      doctor: record.doctor || '',
      chiefComplaint: record.complaint || '',
      temperature: record.temperature || null,
      weight: record.weight || null,
      respiration: record.respiration || null,
      heartRate: record.heartRate || null,
      examination: record.examination || {
        earsEyesMouthNose: 'normal',
        bonesMuscles: 'normal',
        skinCoat: 'normal',
        lymphNodes: 'normal',
        heartLungs: 'normal',
        abdominalPalpation: 'normal',
      },
      labTests: record.labTests || [],
      diagnosis: record.diagnosis || '',
      treatmentPlan: record.treatmentPlan || '',
      prescriptions: record.prescriptions || [],
      surgeries: record.surgeries || [],
      treatments: record.treatments || [],
      doctorAdvice: record.doctorAdvice || '',
      precautions: record.precautions || '',
      followUpDate: record.followUpDate || null,
    };

    currentTabData.formData = newFormData;
    currentTabData.isModified = false; // 选择已有病历时，标记为未修改
  }
};

const loadPetRecords = (petId: string, tab: PetTab) => {
  // 这里应该根据宠物ID加载病历记录
  // 现在使用模拟数据
  tab.medicalRecords = [
    {
      id: 'MR001',
      recordNumber: 'NO201908070004',
      recordDate: dayjs('2019-08-07'),
      doctor: '孙医生',
      complaint: '宠物食欲不振，精神萎靡',
      temperature: 38.5,
      weight: 4.2,
      respiration: 20,
      heartRate: 120,
      examination: {
        earsEyesMouthNose: 'normal',
        bonesMuscles: 'normal',
        skinCoat: 'abnormal',
        lymphNodes: 'normal',
        heartLungs: 'normal',
        abdominalPalpation: 'normal',
      },
      date: '2019-08-07',
      labTests: [
        { name: '血常规', price: 80 },
        { name: '生化检查', price: 120 },
      ],
      diagnosis: '急性肠胃炎',
      treatmentPlan: '对症治疗，注意饮食',
      prescriptions: [
        {
          group: 'A',
          name: '阿莫西林',
          specification: '0.25g*12片',
          unit: '片',
          usage: '口服',
          dosage: '1片',
          unitPrice: 15,
          quantity: 12,
          addedBy: '孙医生',
          remarks: '每日2次',
        },
      ],
      surgeries: [],
      treatments: [
        {
          name: '静脉输液',
          nurse: '王护士',
          room: '输液室1',
          treatmentDate: dayjs('2019-08-07'),
          price: 50,
        },
      ],
      doctorAdvice: '注意饮食卫生，避免生冷食物，按时服药',
      precautions: '保持环境清洁，避免与其他宠物接触',
      followUpDate: dayjs('2019-08-10'),
      status: 'confirmed', // 已确认状态
    },
    {
      id: 'MR002',
      recordNumber: 'NO201908050003',
      recordDate: dayjs('2019-08-05'),
      doctor: '李医生',
      complaint: '皮肤瘙痒，脱毛',
      temperature: 38.2,
      weight: 4,
      respiration: 18,
      heartRate: 110,
      examination: {
        earsEyesMouthNose: 'normal',
        bonesMuscles: 'normal',
        skinCoat: 'abnormal',
        lymphNodes: 'normal',
        heartLungs: 'normal',
        abdominalPalpation: 'normal',
      },
      date: '2019-08-05',
      labTests: [{ name: '皮肤刮片检查', price: 60 }],
      diagnosis: '过敏性皮肤病',
      treatmentPlan: '抗过敏治疗',
      prescriptions: [
        {
          group: 'A',
          name: '泼尼松',
          specification: '5mg*20片',
          unit: '片',
          usage: '口服',
          dosage: '1片',
          unitPrice: 12,
          quantity: 20,
          addedBy: '李医生',
          remarks: '每日1次',
        },
      ],
      surgeries: [],
      treatments: [
        {
          name: '药浴治疗',
          nurse: '张护士',
          room: '治疗室2',
          treatmentDate: dayjs('2019-08-05'),
          price: 80,
        },
      ],
      doctorAdvice: '避免接触过敏原，保持皮肤清洁',
      precautions: '避免使用刺激性洗护用品',
      followUpDate: dayjs('2019-08-12'),
      status: 'confirmed', // 已确认状态
    },
  ];
};

const searchPets = () => {
  // 搜索逻辑已在计算属性中实现
};

const searchTodayPets = () => {
  // 搜索逻辑已在计算属性中实现
};

const handlePetSearch = (keyword: string) => {
  // 处理宠物搜索
  searchQuery.value = keyword;
};

const showNewMedicalRecord = () => {
  const currentTabData = currentTab.value;
  if (!currentTabData) {
    message.warning('请先选择宠物');
    return;
  }

  // 打开病例管理模态框
  selectedPetForCase.value = currentTabData.pet;
  caseManagementVisible.value = true;
};

// 住院管理相关方法
const showNewInpatient = () => {
  const currentTabData = currentTab.value;
  if (!currentTabData) {
    message.warning('请先选择宠物');
    return;
  }

  // 创建新的住院组
  const newInpatientGroup = {
    id: `IG${Date.now()}`,
    petId: currentTabData.pet.id,
    admissionDate: dayjs(),
    inpatientName: '', // 新增：住院名字字段;
    conditionType: '',
    responsibleDoctor: '',
    dischargeMethod: 'manual',
    dischargeDate: null,
    remarks: '',
    status: 'active',
    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  };

  console.log('新建住院组:', {
    id: newInpatientGroup.id,
    name: newInpatientGroup.inpatientName,
    status: newInpatientGroup.status,
  });

  // 确保inpatientGroups数组存在
  if (!currentTabData.inpatientGroups) {
    currentTabData.inpatientGroups = [];
  }
  currentTabData.inpatientGroups.unshift(newInpatientGroup);
  currentTabData.currentInpatientGroup = newInpatientGroup;

  // 重置住院表单数据
  currentTabData.inpatientFormData = {
    admissionDate: dayjs(),
    inpatientName: '', // 新增：住院名字字段;
    conditionType: '',
    responsibleDoctor: '',
    dischargeMethod: 'manual',
    dischargeDate: null,
    remarks: '',
  };

  recordsTab.value = 'inpatient';
  message.success('新建住院成功！');
};

// 获取当前住院组的病历记录
const getCurrentInpatientRecords = () => {
  const currentTabData = currentTab.value;
  if (!currentTabData || !currentTabData.currentInpatientGroup) {
    return [];
  }

  const currentGroupId = currentTabData.currentInpatientGroup.id;

  // 从全局住院记录中筛选出属于当前住院组的记录
  const groupRecords = (currentTabData.inpatientRecords || []).filter(
    (record: any) => record.inpatientGroupId === currentGroupId,
  );

  console.log('获取当前住院组记录:', {
    groupId: currentGroupId,
    groupName: currentTabData.currentInpatientGroup.inpatientName,
    totalRecords: currentTabData.inpatientRecords?.length || 0,
    groupRecords: groupRecords.length,
  });

  return groupRecords;
};

const selectInpatientGroup = (inpatientGroup: any) => {
  const currentTabData = currentTab.value;
  if (currentTabData) {
    console.log('=== 选择住院组开始 ===');
    console.log('点击的住院组:', {
      id: inpatientGroup.id,
      name: inpatientGroup.inpatientName,
      status: inpatientGroup.status,
    });
    console.log(
      '选择前的currentInpatientGroup:',
      currentTabData.currentInpatientGroup?.id,
    );

    // 设置当前选中的住院组
    currentTabData.currentInpatientGroup = { ...inpatientGroup };

    // 根据选择的住院组更新formData
    currentTabData.inpatientFormData = {
      admissionDate: inpatientGroup.admissionDate || dayjs(),
      inpatientName: inpatientGroup.inpatientName || '', // 新增：住院名字字段;
      conditionType: inpatientGroup.conditionType || '',
      responsibleDoctor: inpatientGroup.responsibleDoctor || '',
      dischargeMethod: inpatientGroup.dischargeMethod || 'manual',
      dischargeDate: inpatientGroup.dischargeDate || null,
      remarks: inpatientGroup.remarks || '',
    };

    // 确保切换到住院管理tab
    recordsTab.value = 'inpatient';

    console.log(
      '选择后的currentInpatientGroup:',
      currentTabData.currentInpatientGroup.id,
    );
    console.log('=== 选择住院组完成 ===');
  }
};

const handleInpatientSave = (data: any) => {
  const currentTabData = currentTab.value;
  if (currentTabData && currentTabData.currentInpatientGroup) {
    console.log('保存住院信息:', {
      groupId: currentTabData.currentInpatientGroup.id,
      groupName: currentTabData.currentInpatientGroup.inpatientName,
      data,
    });

    // 更新当前住院组记录的内容
    Object.assign(currentTabData.currentInpatientGroup, data);

    // 同时更新住院组列表中的对应记录
    if (currentTabData.inpatientGroups) {
      const groupIndex = currentTabData.inpatientGroups.findIndex(
        (group) => group.id === currentTabData.currentInpatientGroup?.id,
      );
      if (groupIndex !== -1 && currentTabData.inpatientGroups[groupIndex]) {
        Object.assign(
          currentTabData.inpatientGroups[groupIndex],
          currentTabData.currentInpatientGroup,
        );
      }
    }

    // 如果data包含records，更新住院记录
    if (data.records && Array.isArray(data.records)) {
      // 移除当前住院组的所有记录
      currentTabData.inpatientRecords = (
        currentTabData.inpatientRecords || []
      ).filter(
        (record: any) =>
          record.inpatientGroupId !== currentTabData.currentInpatientGroup?.id,
      );

      // 添加新的记录
      data.records.forEach((record: any) => {
        if (!record.inpatientGroupId) {
          record.inpatientGroupId = currentTabData.currentInpatientGroup?.id;
        }
        currentTabData.inpatientRecords.push(record);
      });

      console.log('更新住院记录:', {
        groupId: currentTabData.currentInpatientGroup.id,
        recordsCount: data.records.length,
        totalRecords: currentTabData.inpatientRecords.length,
      });
    }

    message.success('住院信息保存成功！');
  }
};

const handleAddInpatientRecord = (data: any) => {
  // 创建新的住院病历记录
  const newRecord = {
    id: `IR${Date.now()}`,
    recordNumber: `IN${dayjs().format('YYYYMMDD')}${String(Math.floor(Math.random() * 10_000)).padStart(4, '0')}`,
    recordDate: dayjs(),
    doctor: data.record.doctor,
    complaint: data.record.complaint,
    examination: {
      earsEyesMouthNose: 'normal',
      bonesMuscles: 'normal',
      skinCoat: 'normal',
      lymphNodes: 'normal',
      heartLungs: 'normal',
      abdominalPalpation: 'normal',
    },
    date: dayjs().format('YYYY-MM-DD'),
    status: 'draft' as const,
    // 标记为住院病历;
    isInpatientRecord: true,
    inpatientGroupId: data.inpatientData.id,
  };

  // 添加到当前标签页的住院病历列表
  const currentTabData = currentTab.value;
  if (currentTabData) {
    if (!currentTabData.inpatientRecords) {
      currentTabData.inpatientRecords = [];
    }
    currentTabData.inpatientRecords.unshift(newRecord);

    // 切换到病历tab并编辑新病历
    recordsTab.value = 'case';
    currentTabData.currentRecord = newRecord;
    currentTabData.formData = {
      recordDate: newRecord.recordDate,
      doctor: newRecord.doctor,
      chiefComplaint: newRecord.complaint,
      examination: newRecord.examination,
      status: 'draft',
    };
    currentTabData.isModified = true;
  }
};

const handleEditInpatientRecord = (data: any) => {
  // 切换到病历tab并编辑现有病历
  recordsTab.value = 'case';
  const currentTabData = currentTab.value;
  if (currentTabData) {
    currentTabData.currentRecord = data.record;
    currentTabData.formData = {
      recordDate:
        data.record.recordDate && dayjs(data.record.recordDate).isValid()
          ? dayjs(data.record.recordDate)
          : dayjs(),
      doctor: data.record.doctor,
      chiefComplaint: data.record.complaint,
      examination: data.record.examination || {
        earsEyesMouthNose: 'normal',
        bonesMuscles: 'normal',
        skinCoat: 'normal',
        lymphNodes: 'normal',
        heartLungs: 'normal',
        abdominalPalpation: 'normal',
      },
      status: data.record.status,
    };
    currentTabData.isModified = true;
  }
};

const handleGetCustomerRecords = (_pet: any) => {
  // 获取当前顾客的所有病历记录
  const currentTabData = currentTab.value;
  if (currentTabData) {
    // 合并普通病历和住院病历
    const allRecords = [
      ...currentTabData.medicalRecords,
      ...(currentTabData.inpatientRecords || []),
    ];

    // 通过ref传递给InpatientGroup组件
    if (inpatientGroupRef.value) {
      inpatientGroupRef.value.setCustomerRecords(allRecords);
    }
  }
};

// 病例管理相关方法
const handleCreateNewCase = (pet: Pet) => {
  const currentTabData = currentTab.value;
  if (!currentTabData) {
    message.warning('请先选择宠物');
    return;
  }

  // 创建新的空白病历记录
  const newRecord: MedicalRecord = {
    id: `MR${Date.now()}`,
    recordNumber: `NO${dayjs().format('YYYYMMDD')}${String(Math.floor(Math.random() * 10_000)).padStart(4, '0')}`,
    recordDate: dayjs(),
    doctor: '',
    complaint: '',
    examination: {
      earsEyesMouthNose: 'normal',
      bonesMuscles: 'normal',
      skinCoat: 'normal',
      lymphNodes: 'normal',
      heartLungs: 'normal',
      abdominalPalpation: 'normal',
    },
    date: dayjs().format('YYYY-MM-DD'),
    status: 'draft', // 默认为草稿状态
  };

  currentTabData.medicalRecords.unshift(newRecord);
  currentTabData.currentRecord = newRecord;

  // 使用nextTick避免递归更新
  nextTick(() => {
    currentTabData.isModified = true;
  });

  recordsTab.value = 'case';
};

const handleSelectHistoricalCase = (historicalRecord: any) => {
  const currentTabData = currentTab.value;
  if (!currentTabData) {
    message.warning('请先选择宠物');
    return;
  }

  // 基于历史病历创建新病历，完整复制原数据
  const newRecord: MedicalRecord = {
    id: `MR${Date.now()}`,
    recordNumber: `NO${dayjs().format('YYYYMMDD')}${String(Math.floor(Math.random() * 10_000)).padStart(4, '0')}`,
    recordDate: dayjs(),
    doctor: historicalRecord.doctor,
    complaint: historicalRecord.chiefComplaint,
    examination: historicalRecord.examination || {
      earsEyesMouthNose: 'normal',
      bonesMuscles: 'normal',
      skinCoat: 'normal',
      lymphNodes: 'normal',
      heartLungs: 'normal',
      abdominalPalpation: 'normal',
    },
    date: dayjs().format('YYYY-MM-DD'),
    status: 'draft', // 复制后默认为草稿状态
  };

  // 创建对应的formData，完整复制历史数据
  const newFormData = {
    recordDate: dayjs(),
    doctor: historicalRecord.doctor,
    chiefComplaint: historicalRecord.chiefComplaint,
    temperature: historicalRecord.temperature || null,
    weight: historicalRecord.weight || null,
    respiration: historicalRecord.respiration || null,
    heartRate: historicalRecord.heartRate || null,
    examination: historicalRecord.examination || {
      earsEyesMouthNose: 'normal',
      bonesMuscles: 'normal',
      skinCoat: 'normal',
      lymphNodes: 'normal',
      heartLungs: 'normal',
      abdominalPalpation: 'normal',
    },
    labTests: historicalRecord.labTests ? [...historicalRecord.labTests] : [],
    diagnosis: historicalRecord.diagnosis,
    treatmentPlan: historicalRecord.treatmentPlan || '',
    prescriptions: historicalRecord.prescriptions
      ? [...historicalRecord.prescriptions]
      : [],
    surgeries: historicalRecord.surgeries
      ? [...historicalRecord.surgeries]
      : [],
    treatments: historicalRecord.treatments
      ? [...historicalRecord.treatments]
      : [],
    doctorAdvice: historicalRecord.doctorAdvice || '',
    precautions: historicalRecord.precautions || '',
    followUpDate: historicalRecord.followUpDate
      ? dayjs(historicalRecord.followUpDate)
      : null,
  };

  currentTabData.medicalRecords.unshift(newRecord);
  currentTabData.currentRecord = newRecord;

  // 使用nextTick避免递归更新
  nextTick(() => {
    currentTabData.formData = newFormData;
    currentTabData.isModified = true;
  });

  recordsTab.value = 'case';

  message.success('已成功复制历史病历数据！');
};

const handleSaveRecord = (record: any) => {
  const currentTabData = currentTab.value;
  if (currentTabData && currentTabData.currentRecord) {
    // 更新当前病历记录的内容
    if (currentTabData.currentRecord) {
      Object.assign(currentTabData.currentRecord, record);
    }

    // 更新当前病历状态为已确认
    currentTabData.currentRecord.status = 'confirmed';

    // 同时更新病历列表中的对应记录
    const recordIndex = currentTabData.medicalRecords.findIndex(
      (r) => r.id === currentTabData.currentRecord?.id,
    );
    if (recordIndex !== -1) {
      // 更新病历列表中的记录
      if (currentTabData.medicalRecords[recordIndex]) {
        Object.assign(currentTabData.medicalRecords[recordIndex], record);
      }
      currentTabData.medicalRecords[recordIndex].status = 'confirmed';
    }

    currentTabData.isModified = false;
    message.success('病历保存成功！');
  }
  // 这里可以添加保存逻辑
};

// 保存草稿
const handleSaveDraft = () => {
  const currentTabData = currentTab.value;
  if (!currentTabData || !currentTabData.currentRecord) {
    message.warning('请先选择病历');
    return;
  }

  // 更新当前病历状态为草稿
  currentTabData.currentRecord.status = 'draft';
  currentTabData.isModified = false;

  message.success('草稿保存成功！');
};

// 删除草稿
const handleDeleteDraft = (record: MedicalRecord) => {
  const currentTabData = currentTab.value;
  if (!currentTabData) {
    message.warning('请先选择宠物');
    return;
  }

  // 只能删除草稿状态的病历
  if (record.status !== 'draft') {
    message.warning('只能删除草稿状态的病历');
    return;
  }

  // 确认删除
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除草稿病历 "${record.recordNumber}" 吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      // 从病历列表中移除
      const index = currentTabData.medicalRecords.findIndex(
        (r) => r.id === record.id,
      );
      if (index !== -1) {
        currentTabData.medicalRecords.splice(index, 1);

        // 如果删除的是当前病历，清空当前病历
        if (currentTabData.currentRecord?.id === record.id) {
          currentTabData.currentRecord = null;
          currentTabData.formData = null;
        }

        message.success('草稿删除成功！');
      }
    },
  });
};

const handlePreviewRecord = () => {
  message.info('预览病历功能');
};

const handlePrintRecord = () => {
  message.info('打印病历功能');
};

const handleFormDataChange = (formData: any) => {
  const currentTabData = currentTab.value;
  if (currentTabData) {
    currentTabData.formData = formData;
    currentTabData.isModified = true;
  }
};

// 保存标签页状态到本地存储
const saveTabsToStorage = () => {
  const tabsData = petTabs.value.map((tab) => ({
    ...tab,
    pet: tab.pet,
    medicalRecords:
      tab.medicalRecords?.map((record) => ({
        ...record,
        recordDate:
          record.recordDate && typeof record.recordDate.format === 'function'
            ? record.recordDate.format('YYYY-MM-DD')
            : record.recordDate,
      })) || [],
    currentRecord: tab.currentRecord
      ? {
          ...tab.currentRecord,
          recordDate:
            tab.currentRecord.recordDate &&
            typeof tab.currentRecord.recordDate.format === 'function'
              ? tab.currentRecord.recordDate.format('YYYY-MM-DD')
              : tab.currentRecord.recordDate,
        }
      : null,
    formData: tab.formData
      ? {
          ...tab.formData,
          recordDate:
            tab.formData.recordDate &&
            typeof tab.formData.recordDate.format === 'function'
              ? tab.formData.recordDate.format('YYYY-MM-DD')
              : null,
          followUpDate:
            tab.formData.followUpDate &&
            typeof tab.formData.followUpDate.format === 'function'
              ? tab.formData.followUpDate.format('YYYY-MM-DD')
              : null,
        }
      : null,
    // 保存住院相关数据
    inpatientGroups:
      tab.inpatientGroups?.map((group: any) => ({
        ...group,
        admissionDate:
          group.admissionDate &&
          typeof group.admissionDate.format === 'function'
            ? group.admissionDate.format('YYYY-MM-DD')
            : group.admissionDate,
        dischargeDate:
          group.dischargeDate &&
          typeof group.dischargeDate.format === 'function'
            ? group.dischargeDate.format('YYYY-MM-DD')
            : group.dischargeDate,
      })) || [],
    currentInpatientGroup: tab.currentInpatientGroup
      ? {
          ...tab.currentInpatientGroup,
          admissionDate:
            tab.currentInpatientGroup.admissionDate &&
            typeof tab.currentInpatientGroup.admissionDate.format === 'function'
              ? tab.currentInpatientGroup.admissionDate.format('YYYY-MM-DD')
              : tab.currentInpatientGroup.admissionDate,
          dischargeDate:
            tab.currentInpatientGroup.dischargeDate &&
            typeof tab.currentInpatientGroup.dischargeDate.format === 'function'
              ? tab.currentInpatientGroup.dischargeDate.format('YYYY-MM-DD')
              : tab.currentInpatientGroup.dischargeDate,
        }
      : null,
    inpatientFormData: tab.inpatientFormData
      ? {
          ...tab.inpatientFormData,
          admissionDate:
            tab.inpatientFormData.admissionDate &&
            typeof tab.inpatientFormData.admissionDate.format === 'function'
              ? tab.inpatientFormData.admissionDate.format('YYYY-MM-DD')
              : tab.inpatientFormData.admissionDate,
          dischargeDate:
            tab.inpatientFormData.dischargeDate &&
            typeof tab.inpatientFormData.dischargeDate.format === 'function'
              ? tab.inpatientFormData.dischargeDate.format('YYYY-MM-DD')
              : tab.inpatientFormData.dischargeDate,
        }
      : null,
  }));

  localStorage.setItem('petMedicalTabs', JSON.stringify(tabsData));
};

// 从本地存储恢复标签页状态
const loadTabsFromStorage = () => {
  const savedTabs = localStorage.getItem('petMedicalTabs');
  if (savedTabs) {
    try {
      const tabsData = JSON.parse(savedTabs);

      // 恢复日期对象
      const restoredTabs = tabsData.map((tab: any) => ({
        ...tab,
        medicalRecords:
          tab.medicalRecords?.map((record: any) => ({
            ...record,
            recordDate:
              record.recordDate && dayjs(record.recordDate).isValid()
                ? dayjs(record.recordDate)
                : dayjs(),
            followUpDate:
              record.followUpDate && dayjs(record.followUpDate).isValid()
                ? dayjs(record.followUpDate)
                : null,
          })) || [],
        currentRecord: tab.currentRecord
          ? {
              ...tab.currentRecord,
              recordDate:
                tab.currentRecord.recordDate &&
                dayjs(tab.currentRecord.recordDate).isValid()
                  ? dayjs(tab.currentRecord.recordDate)
                  : dayjs(),
              followUpDate:
                tab.currentRecord.followUpDate &&
                dayjs(tab.currentRecord.followUpDate).isValid()
                  ? dayjs(tab.currentRecord.followUpDate)
                  : null,
            }
          : null,
        formData: tab.formData
          ? {
              ...tab.formData,
              recordDate:
                tab.formData.recordDate &&
                dayjs(tab.formData.recordDate).isValid()
                  ? dayjs(tab.formData.recordDate)
                  : dayjs(),
              followUpDate:
                tab.formData.followUpDate &&
                dayjs(tab.formData.followUpDate).isValid()
                  ? dayjs(tab.formData.followUpDate)
                  : null,
            }
          : null,
        // 恢复住院相关日期
        inpatientGroups:
          tab.inpatientGroups?.map((group: any) => ({
            ...group,
            admissionDate:
              group.admissionDate && dayjs(group.admissionDate).isValid()
                ? dayjs(group.admissionDate)
                : dayjs(),
            dischargeDate:
              group.dischargeDate && dayjs(group.dischargeDate).isValid()
                ? dayjs(group.dischargeDate)
                : null,
          })) || [],
        currentInpatientGroup: tab.currentInpatientGroup
          ? {
              ...tab.currentInpatientGroup,
              admissionDate:
                tab.currentInpatientGroup.admissionDate &&
                dayjs(tab.currentInpatientGroup.admissionDate).isValid()
                  ? dayjs(tab.currentInpatientGroup.admissionDate)
                  : dayjs(),
              dischargeDate:
                tab.currentInpatientGroup.dischargeDate &&
                dayjs(tab.currentInpatientGroup.dischargeDate).isValid()
                  ? dayjs(tab.currentInpatientGroup.dischargeDate)
                  : null,
            }
          : null,
        inpatientFormData: tab.inpatientFormData
          ? {
              ...tab.inpatientFormData,
              admissionDate:
                tab.inpatientFormData.admissionDate &&
                dayjs(tab.inpatientFormData.admissionDate).isValid()
                  ? dayjs(tab.inpatientFormData.admissionDate)
                  : dayjs(),
              dischargeDate:
                tab.inpatientFormData.dischargeDate &&
                dayjs(tab.inpatientFormData.dischargeDate).isValid()
                  ? dayjs(tab.inpatientFormData.dischargeDate)
                  : null,
            }
          : {
              admissionDate: dayjs(),
              conditionType: '',
              responsibleDoctor: '',
              dischargeMethod: 'manual',
              dischargeDate: null,
              remarks: '',
            },
      }));

      petTabs.value = restoredTabs;

      // 恢复第一个标签页为激活状态
      if (petTabs.value.length > 0) {
        activeTabKey.value = petTabs.value[0].id;
      }
    } catch (error) {
      console.error('恢复标签页状态失败:', error);
    }
  }
};

// 标记是否正在初始化
const isInitializing = ref(true);

// 监听标签页变化，自动保存
watch(
  petTabs,
  () => {
    // 只有在非初始化状态下才自动保存
    if (!isInitializing.value) {
      saveTabsToStorage();
    }
  },
  { deep: true },
);

// 初始化数据
onMounted(() => {
  // 从本地存储恢复标签页状态
  loadTabsFromStorage();

  // 标记初始化完成
  isInitializing.value = false;

  // 模拟宠物数据
  pets.value = [
    {
      id: 'P001',
      name: '球球',
      type: '狗',
      age: '3',
      breed: '金毛',
      gender: '公',
      neutered: '否',
      ownerName: '赵女士',
      ownerPhone: '18300138001',
      contact: '18300138001',
      doctor: '孙医生',
      phone: '18300138001',
    },
    {
      id: 'P002',
      name: '兜兜',
      type: '猫',
      age: '2',
      breed: '英短',
      gender: '未知',
      neutered: '否',
      ownerName: '王先生',
      ownerPhone: '18243535',
      contact: '18243535',
      doctor: '孙医生',
      phone: '18243535',
    },
  ];

  // 模拟今日记录
  todayRecords.value = [
    {
      id: 'TR001',
      recordNumber: 'NO201908070005',
      recordDate: dayjs(),
      doctor: '孙医生',
      complaint: '定期体检',
      temperature: 38.2,
      weight: 4,
      respiration: 18,
      heartRate: 110,
      examination: {
        earsEyesMouthNose: 'normal',
        bonesMuscles: 'normal',
        skinCoat: 'normal',
        lymphNodes: 'normal',
        heartLungs: 'normal',
        abdominalPalpation: 'normal',
      },
      date: dayjs().format('YYYY-MM-DD'),
      time: '09:30',
    },
  ];

  // 模拟今日挂号
  todayRegistrations.value = [
    {
      id: 'TR001',
      petId: 'P002',
      petName: '兜兜',
      ownerName: '王先生',
      petType: 'cat',
      doctor: '孙医生',
      contact: '18243535',
    },
    {
      id: 'TR002',
      petId: 'P001',
      petName: '球球',
      ownerName: '赵女士',
      petType: 'dog',
      doctor: '孙医生',
      contact: '183',
    },
  ];

  // 如果没有恢复的标签页，默认选择第一个宠物
  if (petTabs.value.length === 0 && pets.value.length > 0) {
    const firstPet = pets.value[0];
    if (firstPet) {
      selectPet(firstPet);
    }
  }
});
</script>

<template>
  <div class="medical-page">
    <div class="page-container">
      <div class="main-content">
        <!-- 左侧：顾客信息和病历列表 -->
        <div class="left-panel">
          <!-- 宠物标签页 -->
          <div class="pet-tabs-section" v-if="petTabs.length > 0">
            <a-tabs
              v-model:active-key="activeTabKey"
              type="editable-card"
              @edit="closeTab"
              class="pet-tabs"
            >
              <a-tab-pane
                v-for="tab in petTabs"
                :key="tab.id"
                :tab="tab.pet.name + (tab.isModified ? ' *' : '')"
                :closable="true"
              >
                <!-- 顾客信息 -->
                <div class="customer-info-section">
                  <a-card title="顾客信息" class="customer-info-card">
                    <div class="customer-details">
                      <div class="pet-avatar">
                        <a-avatar :size="60">
                          {{ tab.pet.type === '猫' ? '🐱' : '🐕' }}
                        </a-avatar>
                      </div>
                      <div class="pet-info-grid">
                        <div class="info-row">
                          <span class="label">主人:</span>
                          <span class="value">{{ tab.pet.ownerName }}</span>
                        </div>
                        <div class="info-row">
                          <span class="label">电话:</span>
                          <span class="value">{{ tab.pet.contact }}</span>
                        </div>
                        <div class="info-row">
                          <span class="label">种类:</span>
                          <span class="value">{{ tab.pet.type }}</span>
                        </div>
                        <div class="info-row">
                          <span class="label">品种:</span>
                          <span class="value">{{
                            tab.pet.breed || '未填写'
                          }}</span>
                        </div>
                        <div class="info-row">
                          <span class="label">性别:</span>
                          <span class="value">{{
                            tab.pet.gender || '未知'
                          }}</span>
                        </div>
                        <div class="info-row">
                          <span class="label">年龄:</span>
                          <span class="value">{{
                            tab.pet.age || '未填写'
                          }}</span>
                        </div>
                        <div class="info-row">
                          <span class="label">绝育:</span>
                          <span class="value">{{
                            tab.pet.neutered ? '已去势' : '未去势'
                          }}</span>
                        </div>
                      </div>
                    </div>
                  </a-card>
                </div>

                <!-- 病历列表 -->
                <div class="medical-records-section">
                  <a-card title="病历列表" class="records-card">
                    <a-tabs v-model:active-key="recordsTab" size="small">
                      <a-tab-pane key="case" tab="病历列表">
                        <div class="records-list">
                          <div
                            v-for="record in tab.medicalRecords"
                            :key="record.id"
                            class="record-item"
                            :class="{
                              active: tab.currentRecord?.id === record.id,
                            }"
                            @click="selectRecord(record)"
                          >
                            <div class="record-header">
                              <span class="record-date">{{ record.date }}</span>
                              <span class="record-doctor">{{
                                record.doctor
                              }}</span>
                              <span
                                class="record-status"
                                :class="record.status"
                              >
                                {{
                                  record.status === 'draft'
                                    ? '📝 草稿'
                                    : '✅ 已确认'
                                }}
                              </span>
                            </div>
                            <div class="record-summary">
                              <span class="diagnosis">{{
                                record.diagnosis || '暂无诊断'
                              }}</span>
                            </div>
                            <div class="record-actions">
                              <a-button
                                v-if="record.status === 'draft'"
                                type="text"
                                size="small"
                                danger
                                @click.stop="handleDeleteDraft(record)"
                              >
                                删除
                              </a-button>
                            </div>
                          </div>
                        </div>
                      </a-tab-pane>
                      <a-tab-pane key="inpatient" tab="住院管理">
                        <!-- 调试信息 -->
                        <div
                          class="debug-info"
                          style="
                            margin-bottom: 8px;
                            font-size: 12px;
                            color: #999;
                          "
                        >
                          当前选中住院组ID:
                          {{ tab.currentInpatientGroup?.id || '无' }} |
                          住院组总数: {{ tab.inpatientGroups?.length || 0 }}
                        </div>
                        <div class="inpatient-list">
                          <div
                            v-for="group in tab.inpatientGroups"
                            :key="group.id"
                            class="inpatient-item"
                            :class="{
                              active:
                                tab.currentInpatientGroup?.id === group.id,
                            }"
                            @click="selectInpatientGroup(group)"
                            :title="`ID: ${group.id}, 选中状态: ${tab.currentInpatientGroup?.id === group.id}`"
                          >
                            <div class="inpatient-header">
                              <span class="inpatient-date">{{
                                dayjs(group.admissionDate).format('YYYY-MM-DD')
                              }}</span>
                              <span class="inpatient-doctor">{{
                                group.responsibleDoctor
                              }}</span>
                              <span
                                class="inpatient-status"
                                :class="group.status"
                              >
                                {{
                                  group.status === 'active'
                                    ? '🏥 住院中'
                                    : '✅ 已出院'
                                }}
                              </span>
                            </div>
                            <div
                              class="inpatient-name"
                              v-if="group.inpatientName"
                            >
                              <span class="name-label">🏥 {{ group.inpatientName }}</span>
                            </div>
                            <div class="inpatient-condition">
                              {{ group.conditionType }}
                            </div>
                          </div>

                          <!-- 空状态 -->
                          <div
                            v-if="tab.inpatientGroups.length === 0"
                            class="empty-inpatient"
                          >
                            <p>暂无住院记录</p>
                          </div>
                        </div>
                      </a-tab-pane>
                    </a-tabs>

                    <!-- 操作按钮 -->
                    <div class="action-buttons">
                      <a-button type="primary" @click="showNewMedicalRecord">
                        + 新建病历
                      </a-button>
                      <a-button type="primary" @click="showNewInpatient">
                        + 新建住院
                      </a-button>
                    </div>
                  </a-card>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>

          <!-- 空状态 -->
          <div v-else class="no-pets-selected">
            <div class="empty-state">
              <div class="empty-icon">🐾</div>
              <div class="empty-text">请选择宠物开始诊疗</div>
            </div>
          </div>
        </div>

        <!-- 中间：病历表单或住院管理（显要位置） -->
        <div class="center-panel">
          <div v-if="currentTab">
            <!-- 病历表单 -->
            <MedicalRecordForm
              v-if="recordsTab === 'case'"
              :pet="currentTab.pet"
              :record="currentTab.currentRecord"
              :form-data="currentTab.formData"
              @save="handleSaveRecord"
              @save-draft="handleSaveDraft"
              @preview="handlePreviewRecord"
              @print="handlePrintRecord"
              @form-data-change="handleFormDataChange"
            />
            <!-- 住院管理 -->
            <InpatientGroup
              ref="inpatientGroupRef"
              v-else-if="recordsTab === 'inpatient'"
              :pet="currentTab.pet"
              :inpatient-data="
                currentTab.currentInpatientGroup || currentTab.inpatientFormData
              "
              :inpatient-records="getCurrentInpatientRecords()"
              @save="handleInpatientSave"
              @add-record="handleAddInpatientRecord"
              @select-record="selectRecord"
              @add-inpatient-record="handleAddInpatientRecord"
              @edit-inpatient-record="handleEditInpatientRecord"
              @get-customer-records="handleGetCustomerRecords"
            />
          </div>
          <div v-else class="no-pet-selected">
            <div class="empty-state">
              <div class="empty-icon">🐾</div>
              <div class="empty-text">请先选择宠物开始诊疗</div>
            </div>
          </div>
        </div>

        <!-- 右侧：选择宠物 -->
        <div class="right-panel">
          <PetSelector
            :pets="pets"
            :selected-pet="currentTab?.pet || null"
            :active-tab="petSelectionTab"
            title="选择宠物"
            @update:selected-pet="selectPet"
            @update:active-tab="petSelectionTab = $event"
            @search="handlePetSearch"
          />
        </div>
      </div>
    </div>

    <!-- 病例管理模态框 -->
    <CaseManagementModal
      v-model:visible="caseManagementVisible"
      :pet="selectedPetForCase"
      :current-records="currentTab?.medicalRecords"
      @create-new="handleCreateNewCase"
      @select-record="handleSelectHistoricalCase"
    />
  </div>
</template>

<style scoped>
.medical-page {
  position: relative;
  height: 100vh;
  background: #f5f5f5;
}

.page-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.main-content {
  display: flex;
  flex: 1;
  gap: 16px;
  padding: 16px;
  overflow: hidden;
}

.left-panel {
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 320px;
  overflow-y: auto;
}

.center-panel {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.right-panel {
  width: 280px;
  overflow-y: auto;
  background: white;
  border-left: 1px solid #e8e8e8;
}

.pet-tabs-section {
  display: flex;
  flex: 1;
  flex-direction: column;
}

.pet-tabs {
  display: flex;
  flex: 1;
  flex-direction: column;
}

.pet-tabs :deep(.ant-tabs-content-holder) {
  flex: 1;
  overflow: hidden;
}

.pet-tabs :deep(.ant-tabs-tabpane) {
  height: 100%;
  padding: 16px;
  overflow-y: auto;
}

.customer-info-card,
.records-card,
.pet-selection-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.customer-details {
  display: flex;
  gap: 16px;
  align-items: flex-start;
  min-height: 200px;
}

.pet-info-grid {
  display: flex;
  flex: 1;
  flex-direction: column;
  gap: 8px;
}

.info-row {
  display: flex;
  align-items: center;
}

.label {
  width: 80px;
  font-size: 12px;
  font-weight: 600;
  color: #666;
}

.value {
  flex: 1;
  font-size: 12px;
  color: #262626;
}

.records-list {
  max-height: 300px;
  overflow-y: auto;
}

.record-item {
  padding: 12px;
  margin-bottom: 8px;
  cursor: pointer;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  transition: all 0.3s;
}

.record-item:hover {
  border-color: #1890ff;
}

.record-item.active {
  background: #e6f7ff;
  border-color: #1890ff;
}

.record-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 4px;
}

.record-date,
.record-time {
  font-size: 12px;
  color: #666;
}

.record-doctor {
  font-size: 12px;
  font-weight: 600;
  color: #1890ff;
}

.record-complaint {
  font-size: 12px;
  line-height: 1.4;
  color: #262626;
}

.action-buttons {
  display: flex;
  gap: 8px;
  padding: 16px 0 0;
}

.no-pet-selected,
.no-pets-selected {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.empty-state {
  color: #999;
  text-align: center;
}

.empty-icon {
  margin-bottom: 16px;
  font-size: 48px;
}

.empty-text {
  font-size: 16px;
}

:deep(.ant-card-head) {
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-card-body) {
  padding: 16px;
}

:deep(.ant-tabs-nav) {
  margin-bottom: 0;
}

:deep(.ant-tabs-tab) {
  font-size: 12px;
}

:deep(.ant-tabs-tab-active) {
  font-weight: 600;
}

/* 病历状态样式 */
.record-status {
  padding: 2px 6px;
  margin-left: 8px;
  font-size: 12px;
  border-radius: 4px;
}

.record-status.draft {
  color: #fa8c16;
  background: #fff7e6;
  border: 1px solid #ffd591;
}

.record-status.confirmed {
  color: #52c41a;
  background: #f6ffed;
  border: 1px solid #b7eb8f;
}

/* 病历操作按钮样式 */
.record-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.record-item:hover .record-actions {
  opacity: 1;
}

.record-item {
  position: relative;
}

/* 住院管理样式 */
.inpatient-list {
  max-height: 400px;
  overflow-y: auto;
}

.inpatient-item {
  padding: 12px;
  margin-bottom: 8px;
  cursor: pointer;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  transition: all 0.3s;
}

.inpatient-item:hover {
  background-color: #f6ffed;
  border-color: #1890ff;
}

.inpatient-item.active {
  background-color: #e6f7ff;
  border-color: #1890ff;
}

.inpatient-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.inpatient-date {
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.inpatient-doctor {
  margin-left: 8px;
  font-size: 12px;
  color: #666;
}

.inpatient-status {
  padding: 2px 6px;
  margin-left: auto;
  font-size: 12px;
  border-radius: 4px;
}

.inpatient-status.active {
  color: #fa8c16;
  background: #fff7e6;
  border: 1px solid #ffd591;
}

.inpatient-status.discharged {
  color: #52c41a;
  background: #f6ffed;
  border: 1px solid #b7eb8f;
}

.inpatient-condition {
  font-size: 12px;
  color: #666;
}

.inpatient-name {
  margin-top: 4px;
}

.inpatient-name .name-label {
  padding: 2px 6px;
  font-size: 13px;
  font-weight: bold;
  color: #1890ff;
  background: #f0f8ff;
  border: 1px solid #d6e4ff;
  border-radius: 4px;
}
</style>
